package list.answer;

import list.ListNode;

import java.util.Stack;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/6/7 14:07
 * @Version 1.0
 */
public class List01_statck {

    public static ListNode ReverseList(ListNode head) {
        if (head==null) {
            return null;
        }
        //声明一个栈
        Stack<ListNode> stack= new Stack<>();
        //把链表节点全部摘掉放到栈中
        //    next       next       null
        //1--------->2--------->3-------->
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
       //出栈
        //头节点
        ListNode move = stack.pop();
        //头节点，不能移动的
        ListNode fixed = move;
        //栈中的结点全部出栈，然后重新连成一个新的链表
        while (!stack.isEmpty()) {
            ListNode tempNode = stack.pop();
            move.next = tempNode;
            move = move.next;
        }
        //最后一个结点就是反转前的头结点，一定要让他的next
        //等于空，否则会构成环
        move.next = null;
        return fixed;
    }

    public static void main(String[] args) {
        ListNode header=new ListNode(1);
        ListNode two=new ListNode(2);
        ListNode three=new ListNode(3);
        //1-->2
        header.next=two;
        //2-->3
        //header.next.next=three;
        two.next=three;

        System.out.println("----原链表顺序-------");
        show(header);

        System.out.println("\n---反转后的结果------");
        ListNode newNode=ReverseList(header);
        show(newNode);
    }


    private static void show(ListNode head){
        if(head==null){
            System.out.println("空链表");
        }else{
            ListNode temp=head;
            while(temp!=null){
                System.out.print(temp.val+"\t");
                //移后移动一个
                temp=temp.next;
            }
            System.out.println();
        }
    }
}
